/**
 *
 */
package com.nest.WorkNest.act;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.toolbox.NetworkImageView;
import com.lidroid.xutils.exception.HttpException;
import com.nest.WorkNest.R;
import com.nest.WorkNest.api.XutilsPost;
import com.nest.WorkNest.tools.Tool;
import com.nest.WorkNest.tools.VolleyHelper;
import com.nest.WorkNest.tools.imgUtils;
import com.nest.WorkNest.view.SelectPicPopupWindow;

import org.json.JSONObject;

import java.util.HashMap;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 */
public class PersonalCenterAct extends BaseActivity implements OnClickListener {

    @Bind(R.id.replace_headimg)
    RelativeLayout replaceHeadimg;
    @Bind(R.id.mynickname)
    TextView mynickname;
    @Bind(R.id.rel_nickname)
    RelativeLayout relNickname;
    @Bind(R.id.myname)
    TextView tvmyname;
    @Bind(R.id.rel_name)
    RelativeLayout relName;
    @Bind(R.id.introduct)
    TextView myintroduct;
    @Bind(R.id.rel_introduct)
    RelativeLayout relIntroduct;
    @Bind(R.id.myemail)
    TextView myemail;
    @Bind(R.id.rel_email)
    RelativeLayout relEmail;
    @Bind(R.id.myphone)
    TextView myphone;
    @Bind(R.id.rel_phone)
    RelativeLayout relPhone;
    @Bind(R.id.mycompanyname)
    TextView mycompanyname;
    @Bind(R.id.rel_companyname)
    RelativeLayout relCompanyname;
    @Bind(R.id.myIDnumbers)
    TextView myIDnumbers;
    @Bind(R.id.rel_IDnumbers)
    RelativeLayout relIDnumbers;
    @Bind(R.id.mystoreLink)
    TextView mystoreLink;
    @Bind(R.id.rel_storeLink)
    RelativeLayout relStoreLink;
    @Bind(R.id.mypayWay)
    TextView mypayWay;
    @Bind(R.id.rel_payWay)
    RelativeLayout relPayWay;
    @Bind(R.id.rel_address)
    RelativeLayout relAddress;
    //    private RelativeLayout replace_headimg, rel_nickname, rel_name, rel_introduct, rel_birthday,
//            rel_email,rel_phone, rel_companyname,rel_IDnumbers,rel_storeLink,rel_payWay;
    private NetworkImageView user_head;// 用户头像
    private Button btn_personcenter_logout;
    //    private RelativeLayout rel_address;
    private SelectPicPopupWindow mPicPopupWindow;// 图片选择
    private Context context = PersonalCenterAct.this;
    private Intent mIntent;
    private String nickname, email, intro, myname, payway, idnum, companyname, storelink, phone;
    private HashMap<String, String> user;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_personal_information);
        ButterKnife.bind(this);
        initBar();
        actionbar_side_tab_name.setVisibility(View.VISIBLE);
        actionbar_side_tab_name.setText("个人信息");
        ll_iv_actionbar_tab_side_left.setVisibility(View.VISIBLE);
        tv_actionbar_tab_side_right.setVisibility(View.VISIBLE);
        tv_actionbar_tab_side_right.setText("保存");
        tv_actionbar_tab_side_right.setOnClickListener(this);
        ll_iv_actionbar_tab_side_left.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (user != null) {
                    new AlertDialog.Builder(context).setTitle("删除提示").setMessage("您还未保存用户信息，确认退出吗？")
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    finish();
                                }

                            }).setNegativeButton("取消", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    }).show();
                } else {
                    finish();
                }

            }
        });
        loadPerson();
        initData();
    }

    private void initData() {
        btn_personcenter_logout = (Button) findViewById(R.id.btn_personcenter_logout);
        user_head = (NetworkImageView) findViewById(R.id.frame_myself_personal_user_img);
        user_head.setErrorImageResId(R.drawable.default_image);
        user_head.setIndirectBitmapListener(new NetworkImageView.IndirectBitmapListener() {
            @Override
            public Bitmap indirectBitmap(Bitmap bitmap) {
                if (bitmap != null) {
                    return imgUtils.toRoundBitmap(bitmap);
                }
                return null;
            }
        });
        String imgUrl = getIntent().getStringExtra("imgUrl");
        if (!TextUtils.isEmpty(imgUrl))
            if (!imgUrl.substring(0, 1).equals("h") && !imgUrl.substring(0, 1).equals("H")) {
                imgUrl = "http://" + imgUrl;
            }
        user_head.setImageUrl(imgUrl, VolleyHelper.getInstance(this).getImageLoader());
        replaceHeadimg.setOnClickListener(this);
        relNickname.setOnClickListener(this);
        relName.setOnClickListener(this);
        relPhone.setOnClickListener(this);
        btn_personcenter_logout.setOnClickListener(this);
        relAddress.setOnClickListener(this);
        relIntroduct.setOnClickListener(this);
        relEmail.setOnClickListener(this);
        relCompanyname.setOnClickListener(this);
        relIDnumbers.setOnClickListener(this);
        relStoreLink.setOnClickListener(this);
        relPayWay.setOnClickListener(this);
    }

    public void loadPerson() {
        XutilsPost xutilsPost = new XutilsPost();
        XutilsPost.IOAuthCallBack ioAuthCallBack = new XutilsPost.IOAuthCallBack() {
            @Override
            public void getIOAuthCallBack(String result) {
                JSONObject jsonObject = Tool
                        .getJsonObject(result);
                if (Tool.getString(jsonObject, "resultCode").equals("0")) {
                    String userinfo = Tool.getString(jsonObject, "user");
                    HashMap<String, String> user = Tool.getMapByJsonObj(userinfo);
                    mynickname.setText(user.get("nickName"));
                    tvmyname.setText(user.get("realName"));
                    myintroduct.setText(user.get("introduction"));
                    myemail.setText(user.get("email"));
                    myphone.setText(user.get("cellPhone"));
                    mycompanyname.setText(user.get("cellPhone"));
                    myIDnumbers.setText(user.get("identificationNumber"));
                    mystoreLink.setText(user.get("identificationNumber"));
                } else if (Tool.getString(result, "resultCode").equals("9001")) {
                    showToast("token已过期，请重新登录");
                    Intent intent = new Intent(context, LoginAct.class);
                    startActivity(intent);
                    finish();
                }
            }

            @Override
            public void getDealException(HttpException httpException, String result) {

            }

            @Override
            public void getLoadingCallBack(long total, long current, boolean isUploading) {

            }
        };
        xutilsPost.doPostUserDetail(context, ioAuthCallBack);

    }

    @Override
    public void onClick(View v) {
        mIntent = new Intent(context, UpdateUser.class);
        switch (v.getId()) {

            case R.id.replace_headimg:// 选择图片
                photoRefresh(user_head);
                break;
            case R.id.rel_nickname:  // 昵称
                mIntent.putExtra("type", "nickname");
                startActivityForResult(mIntent, 1);
                break;
            case R.id.rel_name:
                // 真实姓名
                mIntent.putExtra("type", "myname");
                startActivityForResult(mIntent, 2);
                break;
            case R.id.rel_introduct:
                mIntent.putExtra("type", "intro");
                startActivityForResult(mIntent, 3);
                break;
            case R.id.rel_email:
                mIntent.putExtra("type", "email");
                startActivityForResult(mIntent, 4);
                break;
            case R.id.rel_payWay:
                mIntent.putExtra("type", "payway");
                startActivityForResult(mIntent, 5);
                break;
            case R.id.rel_IDnumbers:
                mIntent.putExtra("type", "idnum");
                startActivityForResult(mIntent, 6);
                break;
            case R.id.rel_companyname:
                mIntent.putExtra("type", "companyname");
                startActivityForResult(mIntent, 7);
                break;
            case R.id.rel_storeLink:
                mIntent.putExtra("type", "storelink");
                startActivityForResult(mIntent, 8);
                break;
            case R.id.rel_phone:
                mIntent.putExtra("type", "phone");
                startActivityForResult(mIntent, 9);
                break;
            case R.id.rel_address:
                Intent addressIntent = new Intent(context, AddressManagerAct.class);
                startActivity(addressIntent);
                break;
            case R.id.btn_personcenter_logout:
                clearLogininfo();
                loadLogout();
                break;
            case R.id.tv_actionbar_tab_side_right:
                loadUpdate();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (mPicPopupWindow != null) {
            mPicPopupWindow.onActivityResult(requestCode, resultCode, data);
        }
        user = new HashMap<>();
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 1:
                    nickname = data.getStringExtra("nickname");
                    mynickname.setText(nickname);
                    mIntent.putExtra("nickname", nickname);
                    user.put("nickname", nickname);
                    break;
                case 2:
                    myname = data.getStringExtra("myname");
                    tvmyname.setText(myname);
                    mIntent.putExtra("myname", myname);
                    user.put("myname", myname);
                    break;
                case 3:
                    intro = data.getStringExtra("intro");
                    myintroduct.setText(intro);
                    mIntent.putExtra("intro", intro);
                    user.put("intro", intro);
                    break;
                case 4:
                    email = data.getStringExtra("email");
                    myemail.setText(email);
                    mIntent.putExtra("email", email);
                    user.put("email", email);
                    break;
                case 5:
                    payway = data.getStringExtra("payway");
                    mypayWay.setText("payway");
                    mIntent.putExtra("payway", payway);
                    user.put("payway", payway);
                    break;
                case 6:
                    idnum = data.getStringExtra("idnum");
                    myIDnumbers.setText(idnum);
                    mIntent.putExtra("idnum", idnum);
                    user.put("idnum", idnum);
                    break;
                case 7:
                    companyname = data.getStringExtra("companyname");
                    mycompanyname.setText(companyname);
                    mIntent.putExtra("companyname", companyname);
                    user.put("companyname", companyname);
                    break;
                case 8:
                    storelink = data.getStringExtra("storelink");
                    mystoreLink.setText(storelink);
                    mIntent.putExtra("storelink", storelink);
                    user.put("storelink", storelink);
                    break;
                case 9:
                    phone = data.getStringExtra("phone");
                    myphone.setText(phone);
                    mIntent.putExtra("phone", phone);
                    user.put("phone", phone);
                    break;
            }
        }
    }

    private void photoRefresh(final ImageView view) {
        // 上传头像
        if (mPicPopupWindow == null) {
            mPicPopupWindow = new SelectPicPopupWindow(this) {
                @Override
                public void cropPhotoImage(String filePath, final Bitmap bitmap) {
                    loadHeadIcon(filePath);
                    view.setImageBitmap(imgUtils.toRoundBitmap(bitmap));
                }
            };
        }
        mPicPopupWindow.showAtLocation(view, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    private void loadLogout() {
        XutilsPost xutilsPost = new XutilsPost();
        XutilsPost.IOAuthCallBack ioAuthCallBack = new XutilsPost.IOAuthCallBack() {
            @Override
            public void getIOAuthCallBack(String result) {
                JSONObject jsonObject = Tool.getJsonObject(result);
                if (Tool.getString(jsonObject, "resultCode").equals("0")) {
                    showToast("退出成功");
                    finish();
                }
            }

            @Override
            public void getDealException(HttpException httpException, String result) {

            }

            @Override
            public void getLoadingCallBack(long total, long current, boolean isUploading) {

            }
        };
        xutilsPost.doPostLogout(context, ioAuthCallBack);
        showToast("退出成功");
        finish();
    }

    public void loadHeadIcon(String filePath) {
        XutilsPost xutilsPost = new XutilsPost();
        XutilsPost.IOAuthCallBack ioAuthCallBack = new XutilsPost.IOAuthCallBack() {
            @Override
            public void getIOAuthCallBack(String result) {
                if (Tool.getString(result, "resultCode").equals("0")) {

                } else if (Tool.getString(result, "resultCode").equals("9001")) {
                    showToast("token已过期，请重新登录");
                    Intent intent = new Intent(context, LoginAct.class);
                    startActivity(intent);
                    finish();
                }
            }

            @Override
            public void getDealException(HttpException httpException, String result) {

            }

            @Override
            public void getLoadingCallBack(long total, long current, boolean isUploading) {

            }
        };
        xutilsPost.doPostUpfile(context, filePath, ioAuthCallBack);
    }

    public void loadUpdate() {
        XutilsPost xutilsPost = new XutilsPost();
        XutilsPost.IOAuthCallBack ioAuthCallBack = new XutilsPost.IOAuthCallBack() {
            @Override
            public void getIOAuthCallBack(String result) {
                if (Tool.getString(result, "resultCode").equals("0")) {
                    showToast("修改成功");
                } else if (Tool.getString(result, "resultCode").equals("9001")) {
                    showToast("token已过期，请重新登录");
                    Intent intent = new Intent(context, LoginAct.class);
                    startActivity(intent);
                    finish();
                } else {
                    showToast("修改失败");
                }
            }

            @Override
            public void getDealException(HttpException httpException, String result) {

            }

            @Override
            public void getLoadingCallBack(long total, long current, boolean isUploading) {

            }
        };
        xutilsPost.doPostupdateUserInfo(context, user, ioAuthCallBack);
    }
}
